package com.ciwong.epaper.modules.epaper.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.TimeoutError;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.clazz.bean.TeacherClassBean;
import com.ciwong.epaper.modules.epaper.adapter.HotWordAdapter;
import com.ciwong.epaper.modules.epaper.adapter.SearchBookAdapter;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.epaper.bean.SearchBookKeyNameBean;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.me.bean.BooksPage;
import com.ciwong.epaper.modules.me.bean.FavoritesBook;
import com.ciwong.epaper.modules.me.bean.ServiceProductsBean;
import com.ciwong.epaper.modules.me.widget.MarginDecoration;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.widget.PullToRefreshView;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.bean.SchoolDetail;
import com.ciwong.mobilelib.i.BaseQuickOnItemClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseIntentFlag;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by albus on 2017/4/6.
 */

public class SearchBookActivity extends BaseActivity implements PullToRefreshView.OnHeaderRefreshListener,
        View.OnClickListener,
        PullToRefreshView.OnFooterRefreshListener, AdapterView.OnItemClickListener {
    /**
     * 每页数据大小
     */
    private static final int LOAD_PAGE_SIZE = 15;

    /**
     * 搜索结果显示
     */
    private RecyclerView lv_searchResult;
    /**
     * 正在搜索中的页面
     */
    private RelativeLayout rel_searching;

    /**
     * 搜索结果为空
     */
    private RelativeLayout rel_search_empty;

    private int isOwn;

    /**
     * 搜索关键字
     */
    private EditText edt_searching_book_str;
    /**
     * 搜索中的动画图片
     */
    ImageView iv_searching_book;
    /**
     * 加载更多
     */
    PullToRefreshView plv_searchbook;
    ImageView iv_search_dot1;
    ImageView iv_search_dot2;
    ImageView iv_search_dot3;
    private List<TeacherClassBean> teacherClassBeans = new ArrayList<>();

    private HotWordAdapter hotWordAdapter;
    private List<SearchBookKeyNameBean> searchBookKeyNameBeanList = new ArrayList<SearchBookKeyNameBean>();

    private SearchBookAdapter searchBookadapter;
    private List<BooksPage> searchBookList = new ArrayList<BooksPage>();
    private String classIds;

    //学校id
    private int schoolId;
    //年级id
    private int gradeId;
    //书籍分类,1教材同步 2课外拓展 -1为所有
    private int bookType = -1;
    //关键字搜索
    private String keyWords;

    private int mBookmarkId;

    private int brandId;
    //服务ID
    private int serviceId;

    private int uId;
    private ServiceProductsBean serviceProductsBean;


    @Override
    protected int setView() {
        return R.layout.activity_searchbook;

    }

    /**
     * 清除搜索关键字
     */
    ImageView iv_clear_keywords;

    @Override
    protected void findViews() {
        plv_searchbook = findViewById(R.id.plv_searchbook);
        lv_searchResult = findViewById(R.id.lv_searchbook);
        rel_searching = findViewById(R.id.rel_searching);
        rel_search_empty = findViewById(R.id.rel_search_empty);
        iv_searching_book = findViewById(R.id.iv_searching_book);
        edt_searching_book_str = findViewById(R.id.edt_searching_book_str);
        edt_searching_book_str.setSingleLine();
        iv_search_dot1 = findViewById(R.id.iv_search_dot1);
        iv_search_dot2 = findViewById(R.id.iv_search_dot2);
        iv_search_dot3 = findViewById(R.id.iv_search_dot3);
        iv_clear_keywords = findViewById(R.id.iv_clear_keywords);

    }

    @Override
    protected void initEvent() {

        plv_searchbook.setOnHeaderRefreshListener(this);
        iv_clear_keywords.setOnClickListener(this);
        plv_searchbook.setOnFooterRefreshListener(this);
        edt_searching_book_str.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().isEmpty()) {
                    iv_clear_keywords.setImageResource(R.mipmap.btn_search_empty);
                } else {
                    iv_clear_keywords.setImageResource(R.mipmap.btn_search_clean);
                }
            }
        });
    }


    @Override
    protected void init() {
        brandId = EApplication.BRAND_ID;
        setTitleText("搜索书籍");
        if (searchBookadapter == null) {
            lv_searchResult.setLayoutManager(new GridLayoutManager(SearchBookActivity.this, 3));
            lv_searchResult.addItemDecoration(new MarginDecoration(SearchBookActivity.this));
            searchBookadapter = new SearchBookAdapter(R.layout.item_search_book, searchBookList);
            lv_searchResult.setAdapter(searchBookadapter);
            searchBookadapter.setOnItemClickListener(new BaseQuickOnItemClickListener() {
                @Override
                public void avertRepeatOnClick(BaseQuickAdapter adapter, View view, int position) {
                    try {
                        BooksPage epaperInfo = searchBookList.get(position);
                        setFavoritesBook(epaperInfo);
                    } catch (Exception e) {

                    }
                }
            });
        }
    }

    private void setFavoritesBook(BooksPage epaperInfo) {
        try {
            if (null != epaperInfo) {
                FavoritesBook favoritesBook = new FavoritesBook();
                favoritesBook = new FavoritesBook();
                favoritesBook.setAppId(epaperInfo.getAppId());
                favoritesBook.setBookIntro(epaperInfo.getBookIntro());
                favoritesBook.setBookType(epaperInfo.getBookType());
                favoritesBook.setCover(epaperInfo.getCover());
                favoritesBook.setGrade(epaperInfo.getGrade());
                favoritesBook.setSubject(epaperInfo.getSubject());
                favoritesBook.setIsFree(epaperInfo.getIsFree());
                favoritesBook.setPackageIsFree(epaperInfo.getPackageIsFree());
                favoritesBook.setProductId(epaperInfo.getProductId());
                if (!"".equals(epaperInfo.getPackageId())) {
                    favoritesBook.setPackageId(Integer.valueOf(epaperInfo.getPackageId()));
                }
                favoritesBook.setGradeName(epaperInfo.getGradeName());
                favoritesBook.setRequired(epaperInfo.getRequired());
                if (!"".equals(epaperInfo.getServiceId())) {
                    serviceId = Integer.valueOf(epaperInfo.getServiceId());
                    favoritesBook.setServiceId(Integer.valueOf(epaperInfo.getServiceId()));
                }
                favoritesBook.setServiceName(epaperInfo.getServiceName());
                favoritesBook.setBookType(epaperInfo.getBookType());
                favoritesBook.setTeamId(epaperInfo.getTeamId());
                favoritesBook.setTeamName(epaperInfo.getTeamName());
                favoritesBook.setBookIntro(epaperInfo.getBookIntro());
                favoritesBook.setSort(epaperInfo.getSort());
                favoritesBook.setIstop(epaperInfo.getIstop());
                favoritesBook.setIsPwd(epaperInfo.getIsPwd());
                favoritesBook.setPackageType(epaperInfo.getPackageType());
                if (null != epaperInfo.getProductName()) {
                    favoritesBook.setProductName(epaperInfo.getProductName());
                } else {
                    favoritesBook.setProductName("");
                }
                EpaperJumpManager.jumpToCatalog2(R.string.go_back, SearchBookActivity.this, RequestCode.TeaWorkContent.HOME_WORK, favoritesBook, IntentValue.JumpToBookCatalogType.FROM_NEW_DESK_BOOK, REQ_CODE_JUMP_TO_BOOK_DIRECTORY, favoritesBook.getServiceId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void loadData() {
        getMyOneSchool();
    }

    /**
     * 获取学校信息
     */
    public void getMyOneSchool() {
        SchoolDetail mySchool = EApplication.getInstance().getMySchool();
        if (null == mySchool) {
            return;
        }
        schoolId = mySchool.getSchoolId();
        getMyClass(String.valueOf(brandId), 2, schoolId);
    }


    /**
     * 获取班级列表
     */
    public void getMyClass(String brandId, int userRole, int schoolId) {
        EpaperDao.getInstance().getMyClass(brandId, userRole, schoolId, new BaseExtCallBack(SearchBookActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                }
            }

            @Override
            public void failed(Object data) {

                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data && data instanceof ArrayList) {
                    teacherClassBeans = (List<TeacherClassBean>) data;
                    for (int i = 0; i < teacherClassBeans.size(); i++) {
                        if (i == 0) {
                            classIds = String.valueOf(teacherClassBeans.get(i).getClassId());
                        } else {
                            classIds = classIds + "," + teacherClassBeans.get(i).getClassId();
                        }
                    }
                    getServiceProductsByIdClassids();
                }
            }
        });
    }

    private int curPage = 1;


    public void getServiceProductsByIdClassids() {
        EpaperDao.getInstance().getServiceProductsByIdClassids(brandId, isOwn, mBookmarkId, uId, classIds,"0", schoolId, gradeId, bookType, keyWords, curPage, LOAD_PAGE_SIZE, new BaseExtCallBack(SearchBookActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void success(final Object data) {
                isSearching = false;
                plv_searchbook.onHeaderRefreshComplete();
                plv_searchbook.onFooterRefreshComplete();
                if (null != data) {
                    serviceProductsBean = (ServiceProductsBean) data;
                    List<BooksPage> pageList = serviceProductsBean.getPageList();
                    if (pageList != null && pageList.size() > 0) {
                        //searchBookadapter.setKeyWords(keyWords);//设置搜索关键字高亮
                        reFreshUI(pageList);
                    } else if (curPage == 1) {
                        showEmptyView();
                    } else {
                        showNormalView();
                    }

                    if (searchBookadapter.getItemCount() == serviceProductsBean.getTotalCount()) {
                        plv_searchbook.setFooterState(PullToRefreshView.PULL_TO_NO_MORE);
                    } else {
                        plv_searchbook.setFooterState(PullToRefreshView.PULL_TO_REFRESH);
                    }


                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                plv_searchbook.onHeaderRefreshComplete();
                plv_searchbook.onFooterRefreshComplete();
                isSearching = false;
                showEmptyView();

            }

            @Override
            public void failed(Object data) {
                plv_searchbook.onHeaderRefreshComplete();
                plv_searchbook.onFooterRefreshComplete();
                isSearching = false;
                showEmptyView();
            }

        });
    }

    /**
     *
     */
    private void loadDataFromNet() {
        if (!NetworkUtils.isOnline()) {
            ToastUtil.INSTANCE.toastCenterNoNetError();
            isSearching = false;
            return;
        }
        String putKeyWords = edt_searching_book_str.getText().toString();
        final String newKeyWords = putKeyWords.trim();
        keyWords = putKeyWords;
        try {
            keyWords = URLEncoder.encode(newKeyWords, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (curPage == 1) {
            showSearchingView();
        }
        getServiceProductsByIdClassids();

    }

    private void reFreshUI(List<BooksPage> epaperInfos) {
        showNormalView();
        if (curPage == 1) {
            searchBookList.clear();
            searchBookList.addAll(epaperInfos);
        } else {
            searchBookList.addAll(epaperInfos);
        }
        searchBookadapter.notifyDataSetChanged();
        curPage++;
    }

    private CWDialog mErrorDialog = null;

    /**
     * 添加书籍失败
     */
    public void showErrorDialog() {
        mErrorDialog = new CWDialog(SearchBookActivity.this, false, false)
                .setMessage(getString(R.string.error_add_book), 16, Color.BLACK)
                .setPositiveButton("确定", null, true,
                        getResources().getDrawable(R.drawable.dialog_floor_selector));
        mErrorDialog.show();

    }


    /**
     * 监听键盘，如果是回车，就开始搜索书本
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            /*隐藏软键盘*/
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (inputMethodManager.isActive()) {
                inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
            }
            if (!isSearching) {//防止监听键盘时搜索两次
                isSearching = true;
                curPage = 1;

                loadDataFromNet();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


    /**
     * 是否正在搜索，
     * 防止监听键盘时搜索两次
     */
    private boolean isSearching = false;

    private void showSearchingView() {
        plv_searchbook.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.VISIBLE);
        startLoadingAnim();


    }

    private void startLoadingAnim() {
        iv_search_dot1.setVisibility(View.GONE);
        iv_search_dot2.setVisibility(View.GONE);
        iv_search_dot3.setVisibility(View.GONE);
        loadingAnimHandler.removeMessages(1);
        loadingAnimHandler.removeMessages(2);
        loadingAnimHandler.removeMessages(3);
        loadingAnimHandler.removeMessages(4);
        loadingAnimHandler.sendEmptyMessageDelayed(1, 500);
        loadingAnimHandler.sendEmptyMessageDelayed(2, 1000);
        loadingAnimHandler.sendEmptyMessageDelayed(3, 1500);
        loadingAnimHandler.sendEmptyMessageDelayed(4, 2000);
    }

    private Handler loadingAnimHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    iv_search_dot1.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    iv_search_dot2.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    iv_search_dot3.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    startLoadingAnim();
                    break;
            }
        }
    };

    public void showHotWordView() {
        plv_searchbook.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.GONE);
    }

    public void showNormalView() {
        plv_searchbook.setVisibility(View.VISIBLE);
        rel_search_empty.setVisibility(View.GONE);
        rel_searching.setVisibility(View.GONE);
        removeAnimaMessages();
    }

    public void showEmptyView() {
        plv_searchbook.setVisibility(View.GONE);
        rel_search_empty.setVisibility(View.VISIBLE);
        rel_searching.setVisibility(View.GONE);
        removeAnimaMessages();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeAnimaMessages();
    }

    private void removeAnimaMessages() {
        loadingAnimHandler.removeMessages(1);
        loadingAnimHandler.removeMessages(2);
        loadingAnimHandler.removeMessages(3);
        loadingAnimHandler.removeMessages(4);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        curPage = 1;
//        getServiceStateAndData();
        loadDataFromNet();
    }

    private static final int REQ_CODE_JUMP_TO_BOOK_DIRECTORY = 1;// 去书籍目录

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        loadDataFromNet();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int viewId = parent.getId();
        if (viewId == R.id.lv_searchbook) {//点击搜到的结果书本
            try {
                BooksPage epaperInfo = searchBookadapter.getItem(position);
                if (null != epaperInfo) {
                    FavoritesBook favoritesBook = new FavoritesBook();
                    favoritesBook.setAppId(epaperInfo.getAppId());
                    favoritesBook.setBookIntro(epaperInfo.getBookIntro());
                    favoritesBook.setBookType(epaperInfo.getBookType());
                    favoritesBook.setCover(epaperInfo.getCover());
                    favoritesBook.setGrade(epaperInfo.getGrade());
                    favoritesBook.setSubject(epaperInfo.getSubject());
                    favoritesBook.setIsFree(epaperInfo.getIsFree());
                    favoritesBook.setPackageIsFree(epaperInfo.getPackageIsFree());
                    favoritesBook.setProductId(epaperInfo.getProductId());
                    if (!"".equals(epaperInfo.getPackageId())) {
                        favoritesBook.setPackageId(Integer.valueOf(epaperInfo.getPackageId()));
                    }
                    favoritesBook.setGradeName(epaperInfo.getGradeName());
                    favoritesBook.setRequired(epaperInfo.getRequired());
                    if (!"".equals(epaperInfo.getServiceId())) {
                        serviceId = Integer.valueOf(epaperInfo.getServiceId());
                        favoritesBook.setServiceId(Integer.valueOf(epaperInfo.getServiceId()));
                    }
                    favoritesBook.setServiceName(epaperInfo.getServiceName());
                    favoritesBook.setBookType(epaperInfo.getBookType());
                    favoritesBook.setTeamId(epaperInfo.getTeamId());
                    favoritesBook.setTeamName(epaperInfo.getTeamName());
                    favoritesBook.setBookIntro(epaperInfo.getBookIntro());
                    favoritesBook.setSort(epaperInfo.getSort());
                    favoritesBook.setIstop(epaperInfo.getIstop());
                    favoritesBook.setIsPwd(epaperInfo.getIsPwd());
                    favoritesBook.setPackageType(epaperInfo.getPackageType());
                    if (null != epaperInfo.getProductName()) {
                        favoritesBook.setProductName(epaperInfo.getProductName());
                    } else {
                        favoritesBook.setProductName("");
                    }
                    EpaperJumpManager.jumpToCatalog2(R.string.go_back, SearchBookActivity.this, RequestCode.TeaWorkContent.HOME_WORK, favoritesBook, IntentValue.JumpToBookCatalogType.FROM_NEW_DESK_BOOK, REQ_CODE_JUMP_TO_BOOK_DIRECTORY, serviceId);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQ_CODE_JUMP_TO_BOOK_DIRECTORY && resultCode == Activity.RESULT_OK) { //添加书籍成功
            setResult(RESULT_OK);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_clear_keywords) {//清除搜索关键字
            edt_searching_book_str.setText("");
        }
    }

    @Override
    public void finish() {
        super.finish();
        //overridePendingTransition(R.anim.slide_down, R.anim.quite);
    }
}
